package com.health.trans.kit;

import cn.hutool.core.date.DateUtil;
import com.health.trans.common.util.GenericUtil;
import com.health.trans.pojo.FieldInfo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.List;

/**
 * @author nqlz
 */
public class SpecificKit {
    public static <T, Y extends Comparable<? super Y>> void fieldInfoCondition(FieldInfo a, List<Predicate> predicateList, Root<T> root, CriteriaBuilder cb) {
        Expression<? extends Y> as = root.get(a.getName()).as(a.getType());
        Y value = a.getType().isAssignableFrom(Date.class)? (Y) DateUtil.parseDateTime(a.getValue().toString()) :a.getValue();
        switch (a.getCondition()) {
            case gt: {
                predicateList.add(cb.greaterThan(as, value));
                break;
            }
            case gte: {
                predicateList.add(cb.greaterThanOrEqualTo(as, value));
                break;
            }
            case in: {
                predicateList.add(cb.in(as.in(value)));
                break;
            }
            case lt: {
                predicateList.add(cb.lessThan(as, value));
                break;
            }
            case lte: {
                predicateList.add(cb.lessThanOrEqualTo(as, value));
                break;
            }
            case like: {
                predicateList.add(cb.like(GenericUtil.get(as), "%" + value + "%"));
                break;
            }
            case leftLike: {
                predicateList.add(cb.like(GenericUtil.get(as), "%" + value));
                break;
            }
            case rightLike: {
                predicateList.add(cb.like(GenericUtil.get(as), value + "%"));
                break;
            }
            case notLike: {
                predicateList.add(cb.notLike(GenericUtil.get(as), value + "%"));
                break;
            }
            case between: {
                predicateList.add(cb.between(GenericUtil.get(as), a.getStartTime(), a.getEndTime()));
                break;
            }
            case isNull: {
                predicateList.add(cb.nullif(GenericUtil.get(as), value).isNull());
                break;
            }
            case notNull: {
                predicateList.add(cb.nullif(GenericUtil.get(as), value).isNotNull());
                break;
            }
            case ne: {
                predicateList.add(cb.notEqual(as, value));
                break;
            }
            default: {
                predicateList.add(cb.equal(as, value));
                break;
            }
        }

    }
}
